package com.smile.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.smile.api.OperateLogApi;
import com.smile.api.OssApi;
import com.smile.mapper.*;
import com.smile.model.domain.*;
import com.smile.model.response.response.GetAirportListResponseDTO;
import com.smile.model.response.response.GetDroneByIdResponseDTO;
import com.smile.model.response.response.GetDroneRankResponseDTO;
import com.smile.model.response.response.GetFlightDynamicsResponseDTO;
import com.smile.service.FlightService;
import com.smile.service.SituationScreenService;
import com.smile.service.uitl.CoordinateTransformUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

@Service
@Slf4j
public class FlightServiceImpl implements FlightService {

    @Autowired
    private OssApi ossApi;

    @Autowired
    private AirportMapper airportMapper;


    @Autowired
    private AirportInfoMapper  airportInfoMapper;
    @Autowired
    private OperateLogApi operateLogApi;

    @Autowired
    private AirportDroneMapper airportDroneMapper;

    @Autowired
    private DroneMapper droneMapper;

    @Autowired
    private InspectionTaskMapper  inspectionTaskMapper;

    @Autowired
    private FlightTaskMapper flightTaskMapper;

    @Autowired
    private DeviceModelMapper deviceModelMapper;

    @Autowired
    private FlightStatisticsMapper flightStatisticsMapper;

    private ReentrantLock reentrantLock = new ReentrantLock();
    @Autowired
    private AirLineMapper airLineMapper;

    @Override
    public Map<String,Object> Info(Long userId) throws IOException {
        Map<String,Object> map = new HashMap<>();

        List<GetAirportListResponseDTO> onlineDevice = new ArrayList<>();
        //设备总览
        Map<String,Object> device = new HashMap<>();
        QueryWrapper<FeisuanAirport> queryWrapper = new QueryWrapper<>();
        List<FeisuanAirport> airportList = airportMapper.selectList(queryWrapper);
        Integer airportNum =  airportList.size();
        Integer airportOnlineNum = 0;
        for (FeisuanAirport feisuanAirport : airportList) {
            if(feisuanAirport.getStatus() ==1){
                Duration duration =Duration.between(feisuanAirport.getModifyTime(), LocalDateTime.now());
                if(duration.toSeconds() <10){
                    GetAirportListResponseDTO getAirportListResponseDTO= BeanUtil.copyProperties(feisuanAirport, GetAirportListResponseDTO.class);
                    QueryWrapper<FeisuanAirportInfo> feisuanAirportInfoQueryWrapper = new QueryWrapper<>();
                    feisuanAirportInfoQueryWrapper.eq("gateway_sn", feisuanAirport.getGatewaySn());
                    FeisuanAirportInfo feisuanAirportInfo = airportInfoMapper.selectOne(feisuanAirportInfoQueryWrapper);
                    if(ObjectUtil.isNotNull(feisuanAirportInfo)){
                        getAirportListResponseDTO.setModeCode(feisuanAirportInfo.getModeCode());
                        if (feisuanAirportInfo.getModeCode() == 0) {
                            getAirportListResponseDTO.setFlightStatus(0);
                        }
                        try{
                            CoordinateTransformUtil.Coordinate coordinate = CoordinateTransformUtil.wgs84ToGcj02(getAirportListResponseDTO.getLongitude(), getAirportListResponseDTO.getLatitude());
                            getAirportListResponseDTO.setLatitude(coordinate.getLatitude());
                            getAirportListResponseDTO.setLongitude(coordinate.getLongitude());
                        }catch (Exception e){
                        }
                        onlineDevice.add(getAirportListResponseDTO);
                    }
                    airportOnlineNum++;
                }
            }
        }

        device.put("airportOnlineNum",airportOnlineNum);
        device.put("airportNum",airportNum);

        QueryWrapper<FeisuanDrone> queryWrapper1 = new QueryWrapper<>();
        List<FeisuanDrone> droneList = droneMapper.selectList(queryWrapper1);
        Integer droneNum = droneList.size();
        Integer droneOnlineNum = 0;
        List<GetDroneByIdResponseDTO> onlineDrone = new ArrayList<>();
        for (FeisuanDrone feisuanDrone : droneList) {
            Duration duration =Duration.between(feisuanDrone.getModifyTime(), LocalDateTime.now());
            if (feisuanDrone.getStatus() ==1 && duration.toSeconds() <10){
                try {
                    CoordinateTransformUtil.Coordinate coordinate = CoordinateTransformUtil.wgs84ToGcj02(feisuanDrone.getLongitude(), feisuanDrone.getLatitude());
                    feisuanDrone.setLongitude(coordinate.getLongitude());
                    feisuanDrone.setLatitude(coordinate.getLatitude());
                }catch (Exception e){

                }
                GetDroneByIdResponseDTO getDroneByIdResponseDTO= BeanUtil.copyProperties(feisuanDrone, GetDroneByIdResponseDTO.class);
                onlineDrone.add(getDroneByIdResponseDTO);
                droneOnlineNum++;
            }
        }
        device.put("droneOnlineNum",droneOnlineNum);
        device.put("droneNum",droneNum);
        device.put("otherNum",0);
        map.put("device",device);
        map.put("onlineDrone",onlineDrone);

        map.put("onlineDevice",onlineDevice);

        //飞行数据部分
        Map<String,Object> flightMap = new HashMap<>();
        CountFlight flight = flightTaskMapper.countFlight();
        flightMap.put("flightTime",flight.getTime());
        flightMap.put("flightDistance",flight.getDistance());
        flightMap.put("flightNum",flight.getNum());
        map.put("flight",flightMap);

        //机型占比
        List<ModelType> modelTypes = droneMapper.modelType();
        map.put("modelType",modelTypes);

        //飞行排名
        QueryWrapper<FeisuanDrone> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.orderByDesc("task_count");
        queryWrapper2.last("limit 6");
        List<FeisuanDrone> flightDroneList = droneMapper.selectList(queryWrapper2);
        List<GetDroneRankResponseDTO> rankList = new ArrayList<>();
        for (FeisuanDrone getDroneRankResponseDTO : flightDroneList) {
            GetDroneRankResponseDTO getDroneRankResponseDTO1 = BeanUtil.copyProperties(getDroneRankResponseDTO, GetDroneRankResponseDTO.class);
            if(ObjectUtil.isNotNull(getDroneRankResponseDTO.getModelId())){
                FeisuanDeviceModel feisuanDeviceModel = deviceModelMapper.selectById(getDroneRankResponseDTO.getModelId());
                if(ObjectUtil.isNotNull(feisuanDeviceModel)){
                    getDroneRankResponseDTO1.setModelName(feisuanDeviceModel.getModelName());
                }
            }
            rankList.add(getDroneRankResponseDTO1);
        }
        map.put("rankList",rankList);

        LocalDate currentDate = LocalDate.now(); // 获取当前日期
        System.out.println("当前日期: " + currentDate); // 输出当前日期

        System.out.println("最近七天的日期: ");
        List<Map> maps = new ArrayList<>();

        for (int i = 7; i >= 0; i--) { // 从0开始循环七天
//            LocalDate date = currentDate.minusDays(i); // 计算最近第i天的日期
            LocalDate date = currentDate.minusDays(i); // 计算最近第i天的日期
            Map<String,Object> map1 = new HashMap<>();
            QueryWrapper<FeisuanFlightStatistics> wrapper = new QueryWrapper<>();
            wrapper.eq("statistics_date",date);
            wrapper.select("sum(total_task_distance) as distance");

            Map<String, Object> map2 = flightStatisticsMapper.selectMaps(wrapper).get(0);
            if(ObjectUtil.isNotNull(map2)){
                BigDecimal distance = (BigDecimal) map2.get("distance");
                map1.put("date",date);
                map1.put("distance",distance);
                maps.add(map1);
            }else{
                map1.put("date",date);
                map1.put("distance",0);
                maps.add(map1);
            }
        }
        map.put("distance",maps);

        //飞行动态
//        Flight dynamics
        QueryWrapper<FeisuanFlightTask> queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.eq("status",4);
        queryWrapper3.orderByDesc("id");

        queryWrapper3.last("limit 6");
        List<FeisuanFlightTask> taskList = flightTaskMapper.selectList(queryWrapper3);
        List<GetFlightDynamicsResponseDTO> flightDynamicsList = new ArrayList<>();
        for (FeisuanFlightTask feisuanFlightTask : taskList) {
            GetFlightDynamicsResponseDTO flightDynamicsResponseDTO = new GetFlightDynamicsResponseDTO();
            flightDynamicsResponseDTO.setStartTime(feisuanFlightTask.getStartTime());
            flightDynamicsResponseDTO.setEndTime(feisuanFlightTask.getEndTime());
            flightDynamicsResponseDTO.setId(feisuanFlightTask.getId());

            if(feisuanFlightTask.getTaskType() == 1){
                flightDynamicsResponseDTO.setDistance(feisuanFlightTask.getFlightDistance());
                flightDynamicsResponseDTO.setFlightType("航线任务");
                QueryWrapper<FeisuanInspectionTask>  inspectionTaskQueryWrapper = new QueryWrapper<>();
                inspectionTaskQueryWrapper.eq("flight_id",feisuanFlightTask.getFlightId());
                inspectionTaskQueryWrapper.last("limit 6");

                FeisuanInspectionTask feisuanInspectionTask = inspectionTaskMapper.selectOne(inspectionTaskQueryWrapper);
                if(ObjectUtil.isNotNull(feisuanInspectionTask)){
                    FeisuanAirline feisuanAirline = airLineMapper.selectById(feisuanInspectionTask.getAirlineId());
                    if(ObjectUtil.isNotNull(feisuanAirline)){
                        flightDynamicsResponseDTO.setAirLineName(feisuanAirline.getAirlineName());
                    }
                }
            }else if(feisuanFlightTask.getTaskType() == 2){
                flightDynamicsResponseDTO.setFlightType("一键起飞");
                flightDynamicsResponseDTO.setAirLineName("-");
            }
            flightDynamicsList.add(flightDynamicsResponseDTO);
        }
        map.put("flightDynamics",flightDynamicsList);
        return map;
    }


}
